

/** 
 * to use apply the following grant as database root :
 * 
 *  GRANT USAGE ON *.* TO 'BugTrackUser'@'localhost'                             | 
 *  GRANT SELECT, INSERT, UPDATE ON `BugTracker`.* TO 'BugTrackUser'@'localhost' 
 * 
 */


package org.teama;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import static java.util.logging.Level.INFO;
import java.util.logging.Logger;


public class DBconnect {
    private static Logger logger = null;
    private static Handler logHandler = null;
    
    private static final DBconnect instance = new DBconnect();
    
    /* just hard coding these - they could be passed in for more flexability */
    public static final String URL = "jdbc:mysql://localhost/BugTracker";
    public static final String USER = "BugTrackUser";
    public static final String PASSWORD = "";
    public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";    
       
    /* construct, load driver, and setup logging */
    private DBconnect() {
    	try {
    	   Class.forName(DRIVER_CLASS);
    	} catch (ClassNotFoundException e) {
    	  System.out.println(e);
    	}
    } 
    
    public static Logger getLogger() {
        if(logger == null){
            logger = Logger.getLogger(UserDA.class.getName());
            logger.setLevel(INFO);
            logHandler = getLogHandler();
        }
        return(logger);
    }
    
    private static Handler getLogHandler() {
        if (logHandler == null) {
            try {
                logHandler = new FileHandler("/tmp/DALog%g.txt");
                logHandler.setLevel(INFO);
                logger.addHandler(logHandler);
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                logger.log(Level.SEVERE, null, ex);
            }
        }
        return logHandler;
    }
    
    /* create a connection - private */
    private Connection createConnection() throws SQLException {
       return DriverManager.getConnection(URL, USER, PASSWORD);
       
    }  
   
    /* get a connection to the database */
    public static Connection getConnection() throws SQLException {
      	 System.out.println("Connecting to MySQL");
         return instance.createConnection();
    }    
}